<template>
    <div>
        <div class="flex" style="margin-bottom: 1.5%">
            <a-tooltip content="请输入原票号">
                <a-input v-model="objectData.ticket_number" placeholder="请输入原票号" allow-clear style="width:calc((100% - 64px) / 6);margin-right:16px;" />
            </a-tooltip>
            <a-tooltip content="请输入箱号">
                <a-input v-model="objectData.box" placeholder="请输入箱号;多个搜索','隔开" allow-clear style="width:calc((100% - 64px) / 6);margin-right:16px;" />
            </a-tooltip>
            <a-tooltip content="请输入车号">
                <a-input v-model="objectData.car_no" placeholder="请输入车号;多个搜索','隔开" allow-clear style="width:calc((100% - 64px) / 6);margin-right:16px;" />
            </a-tooltip>
            <div class="flex" style="width:calc((100% - 64px) / 6);">
                <a-button type="primary" style="margin-right:16px;" @click="handleSouSuo(1)">搜索</a-button>
                <a-button @click="handleChongZhi(1)">重置</a-button>
            </div>
        </div>
        <a-table :scroll="{x:'100%'}" :data="chongGouList" :columns="columns" :pagination="false" row-key='id' :row-selection="{type: 'checkbox',showCheckedAll: true,onlyCurrent: false,}"  v-model:selectedKeys="keys" @selection-change="setSelectedKeys">
            <template #dept_id="{ record,rowIndex }">
                <a-select v-model="record.dept_id"
                :options="dept_list" :field-names="{ value: 'id', label: 'name' }" allow-clear allow-search
                placeholder="请选择客户" @change="handleContract(record.dept_id,rowIndex)" :filter-option="filterOption" />
            </template>
            <template #process_time="{record,rowIndex}">
                <a-date-picker
                    style="width: 100%; "
                    show-time
                    :defaultValue="record.process_time"
                    format="YYYY-MM-DD HH:mm"
                    @ok="onOks($event,rowIndex)"
                />
            </template>
            <template #contract_id="{ record,rowIndex }">
                <a-select 
                v-model="record.contract_id" :options="contract_list" :field-names="{ value: 'id', label: 'name' }"
                allow-clear allow-search placeholder="请选择合同" @change="hadnleChangeGoods(record.contract_id,record.transport_type,rowIndex)" />
            </template>
            <template #goods_id="{ record,rowIndex }">
                <a-select  v-model="record.goods_id"
                :options="record.goods_list" :field-names="{ value: 'goods_id', label: 'name' }" allow-clear :loading="loading" @search="handleSearch($event,rowIndex)" :filter-option="false" allow-search
                placeholder="请选择品名" @change="hadnleGoods(record.goods_id,rowIndex)" />
            </template>
            
            <template #hz_weight="{ record }">
                <input v-model="record.hz_weight" placeholder="重量" type="text" class="input" style="width: 100%;" />
            </template>
            <template #bz_weight="{ record }">
                <input v-model="record.bz_weight" placeholder="重量" type="text" class="input" style="width: 100%;" />
            </template>
            <template #jf_weight="{ record }">
                <input v-model="record.jf_weight" placeholder="重量" type="text" class="input" style="width: 100%;" />
            </template>
            <template #cyr_weight="{ record }">
                <input v-model="record.cyr_weight" placeholder="重量" type="text" class="input" style="width: 100%;" />
            </template>
            <template #car_no="{ record }">
                <div class="flex align_center">
                    <input v-model="record.car_type" placeholder="车种" type="text" class="input"  />
                    <div style="margin: 0 2px;">-</div>
                    <div>{{record.car_no}}</div>
                </div>
            </template>
            
            <!-- <template #transport_type="{record,rowIndex}">
                <a-select v-model="record.transport_type"  placeholder="运输方式" :disabled="record.box != ''?true:false">
                    <a-option v-for="(item, index) in yunshuList" :key="index" :value="item.key" :label="item.title" @change="hadnleChangetransport_type(record.transport_type,rowIndex)" />
                </a-select>
            </template>
            <template #serve_type="{record,rowIndex}">
                <a-select v-model="record.serve_type"  placeholder="是否仓储">
                    <a-option v-for="(item, index) in fuwuList" :key="index" :value="item.key" :label="item.title" @change="hadnleChangeserve_type(record.serve_type,rowIndex)" />
                </a-select>
            </template> -->
            <template #caozuo="{record,rowIndex}">
                <a-link @click="handleTongshang(record,rowIndex)" v-if="rowIndex != 0">同上</a-link>
            </template>
            <!-- <template #ec_id="{record,rowIndex}">
                <a-link @click="openFile(record.ec_id)" v-if="record.ec_id != '' && record.ec_id != null">票据</a-link>
                <a-link @click="openFile(record.ec_id)" v-else>-</a-link>
            </template> -->
            
        </a-table>
        <div class="flex" style="justify-content: flex-end;margin-top: 1.5%;">
            <a-pagination :total="chongGouTotal" :page-size-options="[10,20,50,100,200]" @page-size-change='handlepageSizeChange' show-page-size @change="handleChange"/>
        </div>
        <div class="flex" style="justify-content: flex-end;margin-top: 1.5%;" >
            <a-button type="primary" @click="handleQuePipei">确认匹配</a-button>
        </div>
    </div>
    
</template>




<script setup>
    import { ref, reactive, onMounted, onActivated, defineProps } from "vue";
    import predictionManage from "@/api/prediction/predictionManage";
    import commonApi from "@/api/common";
    import { request } from "@/utils/request.js";
    import { Message } from "@arco-design/web-vue";
    import { pinyin } from "pinyin-pro";
    const emits = defineEmits(['succ'])
    const keys = ref([])
    const dept_list = ref([])   //  公司列表
    const contract_list = ref([])  // 合同列表
    const goods_list = ref([])  // 品名列表
    const loading = ref(false)
    const objectData = ref({
        page:1,
        pageSize:10,
        ticket_number:'',
        car_no:'',
        box:'',
        is_compled:0
    })
    const handleSearch = (e,index)=>{
        loading.value = true;
        request({
            url: 'goods/manage/index',
            method: 'get',
            params: {
                pageSize: 100,
                name:e
            }
        }).then(res => {
            let _data = res.data.items
            _data.map((v,i)=>{
                v.goods_id = v.id
                v.name = v.type.name + '-' + v.name
            })
            chongGouList.value[index].goods_list = _data
            loading.value = false;
        })
    }
    const filterOption = (v,option)=>{
        return option.keywords.some(keywords=>keywords.includes(v))
    }
    const chongGouTotal = ref(0) 
    const yunshuList = ref([])
    const fuwuList = ref([])
    const chongGouList = ref([])
    const handleTongshang = (row,index)=>{
        if(index > 0){
            chongGouList.value[index].dept_id = chongGouList.value[index - 1].dept_id
            chongGouList.value[index].contract_id = chongGouList.value[index - 1].contract_id
            chongGouList.value[index].goods_id = chongGouList.value[index - 1].goods_id
            chongGouList.value[index].car_type = chongGouList.value[index - 1].car_type
            chongGouList.value[index].goods_list = chongGouList.value[index - 1].goods_list
        }else{
            Message.error('同上失败！')
        }
    }
    const openFile = (id) => {
        // 假设文件URL是http://example.com/file.pdf
        const fileUrl = 'https://ec.95306.cn/goPdf?aqcnsfileId=' + id;
        window.open(fileUrl, '_blank');
    };
    const handleQuePipei = ()=>{
        if(keys.value.length != 0){
            let arr = []
            let zongArr = JSON.parse(JSON.stringify(chongGouList.value))
            keys.value.map((v,i)=>{
                zongArr.map((vv,ii)=>{
                    vv.goods_list = []
                    if(v == vv.id){
                        arr.push(vv)
                    }
                })
            })
            let num = arr.findIndex(item=>{
                return item.dept_id == '' || item.contract_id == '' || item.goods_id == '' || item.car_type == '' || (item.bz_weight - 0) == 0 || (item.hz_weight - 0) == 0 || (item.jf_weight - 0) == 0 || (item.cyr_weight - 0) == 0
            })
            if(num != -1){
                return Message.error('客户、合同、品名、车种不能为空！货重、标重、计费重量、承运人重量不能为0')
            }
            request({
                url: 'send/manage/batUpdate',
                method: 'post',
                data: {
                    items:arr
                }
            }).then(res => {
                emits('succ',false)
            })
            
        }else{
            Message.error('请选择数据~')
        }
    }
    const handleDeptList = () => {   //  获取公司列表
        request({
            url: 'system/dept/remote',
            method: 'post',
            data: {
            openPage: false,
            remoteOption: {
                filter: {
                type: ['=', 2],
                status: ['=',1]
                },
                select: ["id", "name"],
                sort: { id: "desc" }
            }
            }
        }).then(res => {
            res.data.map((v,i)=>{
                    v.keywords = [
                    v.name,
                    pinyin(v.name,{toneType:'none',pattern:'first'}).split(' ').join(''),
                    pinyin(v.name,{toneType:'none',pattern:'first'}).split(' ').join('').toUpperCase()
                    ]
            })
            dept_list.value = res.data
        })
    }
    const handleContract = (id,index) => {   // 获取合同列表
        console.log('index:',index)
        chongGouList.value[index].dept_id = id
        request({
            url: 'system/userContract/remote_prediction?dept_id=' + id,
            method: 'get',
            params: {
            openPage: false,
            }
        }).then(res => {
            contract_list.value = res.data
        })
    }
    const hadnleChangeGoods = (e,transport_type,index) => {   // 品名列表
        console.log(e,contract_list.value)
        contract_list.value.map((v,i)=>{
            if(v.id == e){
                chongGouList.value[index].contract_no = v.contract_no 
            }
        })
        chongGouList.value[index].contract_id = e
        chongGouList.value[index].transport_type = transport_type
        
    }
    const hadnleGoods = (e,index) => {   // 选择品名
        chongGouList.value[index].goods_id = e
    }
    const handleSouSuo = (item) =>{   //搜索
        objectData.value.page = 1
        handleChongGouList()
    }
    const handleChongZhi = (item) =>{   //搜索
        objectData.value.page = 1
        objectData.value.ticket_number = ''
        objectData.value.car_no = ''
        objectData.value.box = ''
        handleChongGouList()
    }
    
    const hadnleChangetransport_type = (e,index) => {   // 选择运输方式
        chongGouList.value[index].transport_type = e
    }
    const hadnleChangeserve_type = (e,index) => {   // 选择是否仓储
        chongGouList.value[index].serve_type = e
    }
    const handleChange = (e)=>{
        console.log('选择页码：',e)
        objectData.value.page = e
        handleChongGouList()
    }
    const handlepageSizeChange = (e)=>{
        console.log('页面数量：',e)
        objectData.value.page = 1
        objectData.value.pageSize = e
        handleChongGouList()
    }
    const setSelectedKeys = (ids)=>{
        keys.value = ids
    }
    
    const handleChongGouList = async () => {
        let list = []
        await request({
            url: 'goods/manage/index',
            method: 'get',
            params:{
                pageSize:100,
            }
        }).then(res => {
            let _data = res.data.items
            // 
            _data.map((v,i)=>{
                v.goods_id = v.id
                v.name =  v.type.name + '-' +  v.name
            })
            list = _data
        })
        request({
            url: 'send/manage/index',
            method: 'get',
            params:objectData.value
        }).then(res => {
            let _data = res.data.items
                _data.map((v, i) => {
                    if (v.load_detail == null) {   // 未生成装卸任务
                        v.load = 3
                    } else if (v.load_detail.detail_load_status == 0) { // 已生成装卸任务
                        v.load = 2
                    } else if (v.load_detail.detail_load_status == 1) { // 已生成装卸任务
                        v.load = 1
                    }
                    v.goods_ids = v.goods_id
                    v.transport_type = v.transport_type + ''
                    v.dept_id = v.dept_id == 0? '' : v.dept_id
                    v.goods_id = v.goods_id == 0? '' : v.goods_id
                    v.contract_id = v.contract_id == 0? '' : v.contract_id
                    v.goods_list = list
                });
                chongGouList.value = _data
                chongGouTotal.value = res.data.pageInfo.total
        })
        
    }
    const open =  (row) => {
        keys.value = []
        
        handleChongGouList()
        handleDeptList()
        commonApi.getDict("transport_type").then((res) => {
            yunshuList.value = res.data;
        });
        commonApi.getDict("serve_type").then((res) => {
            fuwuList.value = res.data;
        });
    }
    
    const columns = reactive([
        
        // {
        //     title: "票据",
        //     dataIndex: "ec_id",
        //     align: "center",
        //     slotName:'ec_id',
        //     width: 70,
        // },
        
        {
            title: "原票号",
            dataIndex: "ticket_number",
            align: "center",
            formType: "input",
            width: 150,
        },
        {
            title: "车号",
            dataIndex: "car_no",
            align: "center",
            formType: "input",
            width: 160,
            slotName:'car_no'
        },
        {
            title: "箱号",
            dataIndex: "box",
            formType: "input",
            align: "center",
            width: 130,
            slotName:'box'
        },
        // {
        //     title: "运输方式",
        //     dataIndex: "transport_type",
        //     align: "center",
        //     slotName:'transport_type',
        //     width: 120,
        // },
        {
            title: "办理时间",
            dataIndex: "process_time",
            align: "center",
            width: 160,
            slotName:'process_time'
        },
        {
            title: "客户",
            dataIndex: "dept_id",
            align: "center",
            width: 160,
            slotName:'dept_id'
        },
        {
            title: "合同号",
            dataIndex: "contract_id",
            align: "center",
            slotName:'contract_id',
            width: 160,
        },
        {
            title: "品名",
            dataIndex: "goods_id",
            align: "center",
            slotName:'goods_id',
            width: 160,
        },
        {
            title: "大票品名",
            dataIndex: "goods_name",
            align: "center",
            width: 120,
        },
        
        {
            title: "标重（吨）",
            dataIndex: "bz_weight",
            align: "center",
            slotName:'bz_weight',
            width: 100,
        },
        {
            title: "货重（吨）",
            dataIndex: "hz_weight",
            align: "center",
            slotName:'hz_weight',
            width: 100,
        },
        {
            title: "计费重量（吨）",
            dataIndex: "jf_weight",
            align: "center",
            slotName:'jf_weight',
            width: 100,
        },
        {
            title: "承运人重量（吨）",
            dataIndex: "cyr_weight",
            align: "center",
            slotName:'cyr_weight',
            width: 100,
        },
        
        {
            title: "操作",
            dataIndex: "",
            align: "center",
            slotName:'caozuo',
            fixed:'right',
            width: 80,
        },
    ]);



    defineExpose({ open });
</script>
<style scoped>
.input {
	width: 60px !important;
	padding: 4px 12px;
	background: #fff;
	border: 1px solid rgba(242, 243, 245);
	border-radius: 4px;
	outline: none;
	/*清除input点击之后的黑色边框*/
}

.input:focus {
	background: #fff;
	border: 1px solid #1e80ff;
}

</style>
<script>
export default { name: "send:pipeiindex" };
</script>
